package com.trace.basic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by denglw on 2020/1/5.<br/>
 * Desc: 原子类
 */
public class Atomic {

    public static void main(String[] args) {
        int threadNum = 10;
        CountDownLatch latch = new CountDownLatch(threadNum);
        AtomicRunnable runnable = new AtomicRunnable(latch, 5000);
//        NoAtomicRunnable runnable = new NoAtomicRunnable(latch, 5000);
        for (int i = 0; i < threadNum; i++) {
            new Thread(runnable, "thr" + i).start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        runnable.printCount();
    }


    static class AtomicRunnable implements Runnable {
        private AtomicInteger count = new AtomicInteger(0);
        private CountDownLatch latch;
        private int times;

        AtomicRunnable(CountDownLatch latch, int times) {
            this.latch = latch;
            this.times = times;
        }

        @Override
        public void run() {
            for (int i = 0; i < times; i++) {
                count.incrementAndGet();
            }
            latch.countDown();
        }

        void printCount() {
            System.out.println("count:: " + count.get());
        }
    }


    static class NoAtomicRunnable implements Runnable {
        private int count = 0;
        private CountDownLatch latch;
        private int times;

        NoAtomicRunnable(CountDownLatch latch, int times) {
            this.latch = latch;
            this.times = times;
        }

        @Override
        public void run() {
            for (int i = 0; i < times; i++) {
                count = count + 1;
            }
            latch.countDown();
        }

        void printCount() {
            System.out.println("count:: " + count);
        }
    }

}
